<template>
  <section>
    <div>
      <header>
        <h1 style="text-align: center">{{ conversationInfo.id }}</h1>
      </header>
      <div id="message-list">
        <div v-for="message in conversationInfo.messages" :key="message.id"
             :class="message.left?'left':'right'">
          <div>
            <!--            <img class="avatar" :src="require('../../assets/Images/'+conversationInfo.imageurl)" alt="">-->
            <Avatar :img-url="getImageurl(message.senderId)" class-type="avatar"></Avatar>
          </div>
          <div>
            <div class="message">
              <Avatar :class-type="'message'" :imgUrl="message.content" v-if="message.contentType==='image'"></Avatar>
              <div v-else-if="message.contentType==='file'" @click="downloadFile(message.content)">
                <h1>文件</h1>
                <p>{{ message.content }}</p>
              </div>
              <pre v-else="">{{ message.content }}</pre>
            </div>
          </div>
        </div>
      </div>
      <div id="message-input">
        <el-upload
            class="upload-demo"
            action="http://81.70.70.110:4396/file/upload"
            :headers="headers"
            :data="{userId,type:'image'}"
            :on-success="handleImageSuccess"
            :show-file-list="false"
            multiple
        >
          <el-button @click="send" id="sendImage" type="primary">发图片</el-button>
        </el-upload>
        <el-upload
            class="upload-demo"
            action="http://81.70.70.110:4396/file/upload"
            :headers="headers"
            :data="{userId,type:'file'}"
            :on-success="handleFileSuccess"
            :show-file-list="false"
            multiple
        >
          <el-button @click="send" id="sendFile" type="primary">发文件</el-button>
        </el-upload>
        <el-button @click="openFiles" id="openFiles" type="primary">打开文件目录</el-button>
        <el-input type="textarea" v-model="currentMessage" @keyup.ctrl.enter.native="send" ref="textDom"
                  rows="10"></el-input>
        <el-button @click="send" id="send" type="primary">发送</el-button>
      </div>
    </div>
  </section>
</template>

<script>
import path from "path";

const fs = require('fs')
import axios from "axios";
import Avatar from "../contact/Avatar";
import {remote} from "electron";

const username = require('os').userInfo().username

export default {
  name: "ConversationDetail",
  components: {Avatar},
  data() {
    return {
      currentMessage: '',
      headers: {
        token: localStorage.getItem('u_token')
      },
      userId: localStorage.getItem('u_id'),
      images: {}
    }
  },
  watch: {
    '$store.getters.currentConversation.messages': {
      handler() {
        this.scrollBottom()
      }
    },
  },
  computed: {
    conversationInfo: function () {
      return this.$store.getters.currentConversation
    },
    getImageurl() {
      return (senderId) => {
        console.log(senderId)
        console.log()
        return this.$store.getters.getImageUrl(senderId)
      }
    },
  },
  methods: {

    writeBinary(filename, buf, callback) {
      const stream = fs.createWriteStream(filename);
      stream.write(buf);
      stream.end();
      stream.on('finish', function () {
        callback();
      });
      stream.on('error', function (err) {
        callback(err);
      })
    },
    downloadFile(savedPath) {
      axios.get("http://81.70.70.110:4396/file/download/" + savedPath, {
        headers: {
          token: localStorage.getItem("u_token")
        },
        responseType: "blob"
      }).then((res) => {
        const url = window.URL.createObjectURL(res.data)
        const link = document.createElement('a')

        link.href = url;
        link.setAttribute('download', savedPath)
        link.click();
      })
    }
    ,
    handleImageSuccess(res) {
      const path = res.data['savedPath']

      const data = {
        type: "message",
        message: {
          content: path,
          senderId: localStorage.getItem('u_id'),
          receiverId: this.conversationInfo.id,
          rawId: 10,
          contentType: 'image'
        }
      }
      console.log('send', data)
      window.ws.send(JSON.stringify(data))
    }
    ,
    handleFileSuccess(res) {
      const path = res.data['savedPath']

      const data = {
        type: "message",
        message: {
          content: path,
          senderId: localStorage.getItem('u_id'),
          receiverId: this.conversationInfo.id,
          rawId: 10,
          contentType: 'file'
        }
      }
      console.log('send', data)
      window.ws.send(JSON.stringify(data))
    }
    ,
    openFiles() {
      console.log(username)
      remote.shell.openItem(`C:\\Users\\${username}\\Downloads`)
    },
    send() {
      const content = this.currentMessage.trim()

      if (content) {
        const data = {
          type: "message",
          message: {
            content: this.currentMessage,
            senderId: localStorage.getItem('u_id'),
            receiverId: this.conversationInfo.id,
            rawId: 10
          }
        }
        console.log('send', data)
        window.ws.send(JSON.stringify(data))
      }

      this.currentMessage = ''
    }
    ,
    scrollBottom() {
      this.$nextTick(() => {
        let msg = document.getElementById('message-list')
        msg.scrollTop = msg.scrollHeight
      })
    }
  },
  mounted() {
    console.log('switchConversation', this.$route.params.id)
    if (this.$route.params.id != 0) {
      this.$store.dispatch('changeCurrentConversationId', this.$route.params.id)
    }
    if (this.$store.state.conversationList.length !== 0) {
      this.scrollBottom()
    }
  }
}
</script>

<style scoped lang="scss">
.left {
  .message {
    font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑 Light", Arial, sans-serif;
    font-size: 12px;
    margin: 0 30px 10px;
    color: white;
    padding: 10px;
    background-color: black;
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;
    border-top-right-radius: 5px;
    //border-top-left-radius: 5px;
    position: relative;
    float: right;

    &:after {
      content: "";
      position: absolute;
      width: 0;
      height: 0;
      border: 4px solid;
      border-right-color: black;
      //border-bottom-color: black;
      border-top-color: black;
      right: 100%;
      //bottom: 0;
      top: 0;
    }
  }
}

.right {
  .message {
    font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑 Light", Arial, sans-serif;
    font-size: 12px;
    margin: 0 30px 10px;
    color: white;
    padding: 10px;
    background-color: black;
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;
    border-top-left-radius: 5px;
    //border-top-left-radius: 5px;
    position: relative;
    float: right;

    &:after {
      content: "";
      position: absolute;
      width: 0;
      height: 0;
      border: 4px solid;
      border-left-color: black;
      //border-bottom-color: black;
      border-top-color: black;
      left: 100%;
      //bottom: 0;
      top: 0;
    }
  }
}


.left, .right {
  display: flex;
  margin: 10px;
}

.left {
  flex-direction: row;
}

.right {
  flex-direction: row-reverse;
}

.avatar {
  background-color: gray;
  width: 40px;
  height: 40px;
  margin: 0 0 0 10px;
  border-radius: 10px;
}

#message-list {
  height: calc(100vh - 222px - 27px);
  overflow-y: scroll;
}

#message-input {
  position: absolute;
  width: calc(100% - 250px - 70px);
  bottom: 0;
}

#send {
  position: absolute;
  bottom: 0;
  right: 0;
}

#sendImage {
  position: absolute;
  left: 0;
  bottom: 0;
  z-index: 1;

}

#sendFile {
  position: absolute;
  left: 84px;
  bottom: 0;
  z-index: 1;
}

#openFiles {
  position: absolute;
  left: 168px;
  bottom: 0;
  z-index: 1;
}
</style>
